
import socket
import time
import json
import threading
import struct
import time
import random

MaxBytes = 1024*1024

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
server.settimeout(60)
host = '0.0.0.0'
# host = socket.gethostname()
port = 6000
server.bind((host, port))        # 绑定端口
client = ''
mutex = threading.Lock()


def main():
    while True:
        server.listen(1)                      # 监听
        try:
            while True:
                global client
                client, addr = server.accept()          # 等待客户端连接
                print(addr, " 连接上了")
                while True:
                    data = client.recv(MaxBytes)
                    if not data:
                        print('数据为空，我要退出了')
                        break
                    localTime = time.asctime(time.localtime(time.time()))
                    print(localTime, ' 接收到数据字节数:', len(data))
                    if data[2] == 1:
                        print("收到心跳")
                        with open('/home/vmuser/work/robot/pyServer/camHB', 'rb') as f:
                            mutex.acquire()
                            heart_ret = client.send(f.read())
                            mutex.release()
                            print("心跳送出：" + str(heart_ret))
                            continue
                    strData = str(data[8:], encoding="utf-8")
                    index = strData.find('}') + 1
                    jsons = json.loads(strData[:index])
                    if jsons['cmd'] == 'ivsresult':
                        with open('/home/vmuser/work/robot/pyServer/camRegiSuccess', 'rb') as f:
                            mutex.acquire()
                            client.send(f.read())
                            mutex.release()
                            continue
        finally:
            server.close()                    # 关闭连接


def send_rand_pai():
    global client
    time.sleep(2)
    while True:
        if hasattr(client, 'send'):
            # time.sleep(0.1)
            time.sleep(random.randint(1, 5))
            with open('/home/vmuser/work/robot/pyServer/camWPai', 'rb') as f:
                try:
                    b = f.read()
                    c = bytearray(b)
                    if random.randint(0, 200) % 3 == 1:
                        c[random.randint(21, 24)] = random.randint(0x30, 0x39)
                    mutex.acquire()
                    bbb = client.send(c)
                    mutex.release()
                    print(bbb)
                except BaseException as e:
                    print(repr(e))


if __name__ == '__main__':
    import os
    print("当前目录:" + os.getcwd())
    t1 = threading.Thread(target=main)
    t2 = threading.Thread(target=send_rand_pai)
    t1.start()
    t2.start()
